package org.sky.lock;

import java.util.Date;

import org.sky.util.ReidsUtil;

import redis.clients.jedis.Jedis;

public class RedisLockUtil {
	/**
	 * 锁默认超时时间
	 */
	private static final int DEFUAL_EXPIRE_TIME_S = 30;

	public static Boolean lock(String key, Long timeOut) throws InterruptedException {
		Jedis jedis = ReidsUtil.getJedis();
		long now = new Date().getTime();
		do {
			Long result = jedis.setnx(key, key);
			if (result == 1) {
				jedis.expire(key, RedisLockUtil.DEFUAL_EXPIRE_TIME_S);
				return Boolean.TRUE;
			}else{
				System.out.println("get lock by key = " + key + " fail");
			}
			Thread.sleep(300);
		} while ((System.currentTimeMillis() - now) < (timeOut*1000));

		ReidsUtil.returnRedis(jedis);

		return Boolean.FALSE;
	}

	public static void unLock(String key) {
		Jedis jedis = ReidsUtil.getJedis();
		jedis.del(key);
		ReidsUtil.returnRedis(jedis);
	}
}
